const {Users} = require('../db/models');
const md5 = require('md5')
const {PwdSalt, TokenSecret} = require('../static/constant')
const jwt = require('jsonwebtoken');

module.exports = class Ctrl {
  constructor(req, res) {
    this.req = req;
    this.res = res;
  }
  checkToken() {
    const token = this.req.headers.accesstoken;
    if(!token) {
      this.sendData({
        code: -666,
        message: '请先登录'
      });
      return false;
    }
    try{
      const ret = jwt.verify(token, TokenSecret)
      return true;
    }catch(err) {
      let message = '用户信息错误'
      if(err.name === 'TokenExpiredError') {
        message = '登录过期'
      }
      this.sendData({
        code: -666,
        message
      });
      return false;
    }
  }
  async addAUser(user) {
    user = new Users(user);
    return new Promise(async (resolve, reject) => {
      await user.save((err, res) => {
        if(err) {
          reject(err)
          this.sendData({
            code: -1000,
            message: '数据库报错',
            data: err,
          });
        }
        if(res) {
          console.log('adduser-->', res);
          resolve(res);
        };
      });
    });
  }
  findUser({username}) {
    return Users.findOne({username});
  }
  async getUserInfo({_id}) {
    if(!_id) {
      return this.sendError('缺少 _id 参数');
    }
    const user = await Users.findOne({_id});
    if(user) {
      return this.success(user);
    }
    this.sendError('获取用户信息失败');
  }
  loginAction() {
    // 接受post数据
    let obj = '';
    const req = this.req;
    req.on('data', data => {
      console.log(data);
      obj += data;
    })
    req.on('end', async () => {
      console.log(obj);
      if(obj) {
        obj = JSON.parse(obj);
      }else{
        obj = {};
      }
      // 校验必填字段
      if (!obj.username) {
        return this.res.end('username 必填');
      }
      if (!obj.password) {
        return this.res.end('password 必填');
      }
      // if (!obj.checkcode) {
      //   return res.end('checkcode 必填');
      // }
      // 校验用户是否重复
      const user = await this.findUser(obj);
      console.log('finduser-->', user);
      // 未找到用户进行注册
      if (!user) {
        console.log(666);
        this.register(obj)
        // 找到用户进行登录
      } else {
        this.login(obj, user)
      }
    })
  }
  // 获取好友列表
  async getFriends() {
    try{
      const users = await Users.find();
      this.success(users);
    }catch(err) {
      this.sendError('数据库报错');
    }
    
  }
  // 返回错误公共方法
  sendError(message) {
    this.sendData({
      code: -1,
      message
    });
  }
  success(data) {
    this.sendData({
      code: 0,
      data,
      message: '请求成功！'
    })
  }
  // 注册
  async register({username, password}) {
    // 密码hash加盐
    const user = await this.addAUser({username, password: md5(password, PwdSalt)});
    console.log('adduser2-->', user);
    this.login({username, password}, user)
  }
  // 登录
  async login({username, password}, user) {
    // const user = await this.findUser({username, password: md5(password, PwdSalt)});
    // 校验密码
    if(user && user.password === md5(password, PwdSalt)) {
      const token = jwt.sign({username, id: user._id}, TokenSecret, {expiresIn: '2h'});
      this.sendData({
        code: 0,
        data: {
          username,
          id: user._id,
          token: token
        },
        message: '登录成功'
      });
    } else {
      this.sendData(
        {
          code: -1,
          message: '用户名或密码错误'
        }
      );
    }
  }
  sendData(data) {
    this.res.end(JSON.stringify(data));
  }
}